package http

import (
	"gitee.com/legend9999/publisher/modle"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

type UserHandler int

func (u *UserHandler) list(c *gin.Context) {
	sessionUser := GetSessionUser(c)
	if sessionUser.Role != 1 {
		c.JSON(http.StatusForbidden, "权限不足")
		return
	}
	users, err := userService.Query()
	if err != nil {
		log.Printf(" err:%s", err)
	}
	c.HTML(http.StatusOK, "user/list.html", newHTMLData(c, users))
}

func (u *UserHandler) create(c *gin.Context) {
	sessionUser := GetSessionUser(c)
	if sessionUser.Role != 1 {
		c.JSON(http.StatusForbidden, "权限不足")
		return
	}
	if c.Request.Method == http.MethodGet {
		c.HTML(http.StatusOK, "user/create.html", newHTMLData(c, nil))
		return
	}
	if c.Request.Method == http.MethodPost {
		newUser := new(modle.User)
		if err := c.ShouldBind(newUser); err != nil {
			c.JSON(http.StatusForbidden, "res")
			c.Abort()
			return
		}
		err := userService.Create(newUser)
		if err != nil {
			log.Printf("userService.Create err:%s", err)
			c.JSON(http.StatusForbidden, err)
			return
		}
		c.JSON(http.StatusOK, "ok")
		return
	}
}

func (u *UserHandler) changePassword(c *gin.Context) {
	user := GetSessionUser(c)
	if c.Request.Method == http.MethodGet {
		c.HTML(http.StatusOK, "user/change_password.html", newHTMLData(c, user))
		return
	}
	if c.PostForm("old_password") != user.Password {
		c.JSON(http.StatusOK, "旧密码不正确")
		return
	}
	confirmPassword := c.PostForm("confirm_password")
	newPassword := c.PostForm("new_password")
	if confirmPassword != newPassword {
		c.JSON(http.StatusOK, "两次密码不一致")
		return
	}
	if len(confirmPassword) < 6 || len(newPassword) < 6 {
		c.JSON(http.StatusOK, "密码不能少于6位")
		return
	}
	user.Password = confirmPassword
	err := userService.Update(user)
	if err != nil {
		log.Printf("userService.Update err:%s", err)
		c.JSON(http.StatusOK, err)
		return
	}
	c.JSON(http.StatusOK, "ok")
	return
}
